import { defineStore } from 'pinia'
import http from '@/utils/http'

interface User {
  username: string
  role: string
}

export const useUserStore = defineStore('user', {
  state: () => ({
    user: null as User | null,
    isLoggedIn: false
  }),
  actions: {
    async checkLogin() {
      try {
        const data: any = await http.get('/user/verify-login/')
        if (data.isLoggedIn) {
          this.user = {
            username: data.username,
            role: data.role
          }
          this.isLoggedIn = true
        } else {
          this.clearUser()
        }
        return this.isLoggedIn
      } catch (error) {
        this.clearUser()
        return false
      }
    },
    setUser(userData: User) {
      this.user = userData
      this.isLoggedIn = true
    },
    clearUser() {
      this.user = null
      this.isLoggedIn = false
    }
  }
})